#include "hpdf.h"
#include <cstdio>
#include <fstream>
#include <iostream>
#include <setjmp.h>
#include <string>
#include <vector>

jmp_buf env;

void error_handler(HPDF_STATUS error_no, HPDF_STATUS detail_no,
                   void *user_data) {
  printf("ERROR: error_no=%04X, detail_no=%u\n", (HPDF_UINT)error_no,
         (HPDF_UINT)detail_no);
  longjmp(env, 1);
}

// 从字体文件中读取所有字符
std::vector<wchar_t> load_font_characters(const std::string &font_file) {
  std::vector<wchar_t> characters;

  std::ifstream font_stream(font_file, std::ios::binary);
  if (!font_stream) {
    std::cerr << "Failed to open font file: " << font_file << std::endl;
    return characters;
  }

  for (wchar_t ch = 0x20; ch <= 0x7E; ++ch) {
    characters.push_back(ch);
  }

  return characters;
}

int main() {
  // 创建PDF文档
  HPDF_Doc pdf = HPDF_New(error_handler, nullptr);
  if (!pdf) {
    std::cerr << "Failed to create PDF object" << std::endl;
    return 1;
  }

  // 加载Arial Unicode MS字体
  const std::string font_file = "./Arial_Unicode_MS.ttf";
  const char *font_name =
      HPDF_LoadTTFontFromFile(pdf, font_file.c_str(), HPDF_TRUE);
  if (!font_name) {
    std::cerr << "Failed to load font: " << font_file << std::endl;
    HPDF_Free(pdf);
    return 1;
  }

  auto hfont = HPDF_GetFont(pdf, font_name, "CP1250");

  // 从字体文件中加载所有字符
  std::vector<wchar_t> characters = load_font_characters(font_file);

  // 排版参数
  const int chars_per_page = 200;
  const int chars_per_line = 10;
  const int lines_per_page = chars_per_page / chars_per_line;
  const float font_size = 12.0;
  const float page_width = 595.0;
  const float page_height = 842.0;
  const float margin = 50.0;
  const float line_height = font_size + 2.0;

  // 写入字符到PDF
  int char_index = 0;
  while (char_index < characters.size()) {
    // 创建新页面
    HPDF_Page page = HPDF_AddPage(pdf);
    HPDF_Page_SetSize(page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT);
    HPDF_Page_SetFontAndSize(page, hfont, font_size);

    // 写入字符到页面
    float x = margin;
    float y = page_height - margin - font_size;
    for (int line = 0; line < lines_per_page && char_index < characters.size();
         ++line) {
      std::wstring line_text;
      for (int col = 0; col < chars_per_line && char_index < characters.size();
           ++col) {
        line_text += characters[char_index++];
      }
      HPDF_Page_BeginText(page);
      HPDF_Page_TextOut(
          page, x, y, std::string(line_text.begin(), line_text.end()).c_str());
      HPDF_Page_EndText(page);
      y -= line_height;
    }
  }

  // 保存PDF到文件
  const std::string output_file = "output.pdf";
  HPDF_SaveToFile(pdf, output_file.c_str());

  // 释放资源
  HPDF_Free(pdf);

  std::cout << "PDF created successfully: " << output_file << std::endl;
  return 0;
}